namespace WinMote7.ViewModels
{
    using System;
    using Caliburn.Micro;
    using System.Collections.Generic;
    using System.Windows;
    using UPnPControllerServices;
    using System.Collections.ObjectModel;
    using System.Net;

    public class MainPageViewModel : INotifyPropertyChangedEx
    {
        readonly INavigationService navigationService;

        public MainPageViewModel(INavigationService navigationService)
        {
            this.navigationService = navigationService;
            PageTitle = "Servers";
            LoadingPanel = true;
            AvailableServers = new ObservableCollection<MediaServer>();

            FindMediaServers();
        }

        private void FindMediaServers()
        {
            UPnPMediaBrowserServiceClient client = new UPnPMediaBrowserServiceClient();

            client.GetAvailableMediaServersCompleted += new EventHandler<GetAvailableMediaServersCompletedEventArgs>(client_GetAvailableMediaServersCompleted);
            client.GetAvailableMediaServersAsync();
        }

        void client_GetAvailableMediaServersCompleted(object sender, GetAvailableMediaServersCompletedEventArgs e)
        {
            AvailableServers.Clear();

            foreach (var result in e.Result)
            {
                if (result.FriendlyName.StartsWith("PS3"))
                {
                    result.IconUrl = "/Resources/PMS.png";
                }
                else
                {
                    result.IconUrl = "/Resources/MediaPlayerServer.png";
                }

                AvailableServers.Add(result);
            }

            LoadingPanel = false;
            NotifyOfPropertyChange("LoadingPanel");
            NotifyOfPropertyChange("NoResultsFound");
        }

        public string PageTitle { get; set; }

        public ObservableCollection<MediaServer> AvailableServers
        {
            get;
            set;
        }

        public void SelectServer(MediaServer from)
        {
            navigationService.Navigate(new Uri(string.Format("/Views/BrowseMedia.xaml?uuid={0}&ServerName={1}", HttpUtility.UrlEncode(from.ServerIdentifier.ToString()), HttpUtility.UrlEncode(from.FriendlyName)), UriKind.RelativeOrAbsolute));
        }

        public bool LoadingPanel
        {
            get;
            set;
        }

        public void NotifyOfPropertyChange(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        public bool NoResultsFound
        {
            get
            {
                return AvailableServers.Count == 0;
            }
        }
    }
}